
// Copyright (C) 2007 Richard Uhler
// This file is part of Esiply.
//
// Esiply is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License, Version 2,
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include <assert.h>
#include <stdio.h>
#include "ErrorObject.h"
#include "Null.h"
#include "Object.h"
#include "Reference.h"
#include "String.h"

Reference::Reference(Value* base, String* name)
    : m_base(base), m_name(name)
{}

ValueType Reference::getType() const
{
    return VT_REFERENCE;
}

Value* Reference::getValue()
{
    // Ecma 8.7.1
    // 1. if Type is not a reference... (it is)
    // 2. Get the base (done).
    // 3. If base is null, throw a ReferenceError exception
    if (m_base->getType() == VT_NULL)
    {
        fprintf(stderr, "NAME is %s\n", m_name->c_str());
        return esiply_throw(ET_REFERENCE,
                "Calling get value on a reference with null base");
    }

    // 4. Call the [[get]] method of base, passing the property name.
    // 5. Return that result
    return m_base->object()->get(m_name);
}

void Reference::putValue(Value* value)
{
    // Ecma 8.7.2
    // 1. if Type is not a reference... (it is)
    // 2. Get the base (done).
    // 3. If base is null, go to step 6.
    if (m_base->getType() == VT_NULL)
    {
        // 6. Call [[put]] for the global object, passing name for name
        // and value for value
        Object::global->put(m_name, value, PA_EMPTY);

        // 7. Return
        return;
    }

    // 4. Call put on base
    // 5. Return
    m_base->object()->put(m_name, value, PA_EMPTY);
    return;
}

Value* Reference::getBase() const
{
    return m_base;
}

String* Reference::getPropertyName() const
{
    return m_name;
}

